﻿using System;
using System.Collections.Generic;
using System.Text;
using DeepEarth.Map.Core;
using DeepEarth.Map.Core.Tiling;

namespace DeepEarth.Map.TileSources
{
    public class MDSMapTileSource : BaseTileSource
    {
        private const int DefaultMaxZoomLevel = 18;
        private const int DefaultTileSize = 256;
        private const string TilePath = "http://t{0}.nowwhere.com.au/18/{3}/{1}/{2}";

        public DateTime? DateMap {get; set;}

        //Constructor Called by XAML instanciation; Wait for MapMode to be set to initialize services
        public MDSMapTileSource()
            : base(MDSTileSourceFactory.StreetMap, (int)Math.Pow(2, DefaultMaxZoomLevel) * DefaultTileSize,
                   (int)Math.Pow(2, DefaultMaxZoomLevel) * DefaultTileSize,
                   DefaultTileSize,
                   DefaultTileSize,
                    0)
        {
        }

        protected override void GetTileLayers(int tileLevel, int tilePositionX, int tilePositionY, IList<object> tileImageLayerSources)
        {
            int zoom = tileLevel-8;
            if (zoom > 0)
            {
                var quadKey = TileXYToQuadKey(tilePositionX, tilePositionY, zoom);
                string url = string.Format(TilePath, (int.Parse(quadKey.Substring(quadKey.Length - 1)) + 1), tilePositionX,
                                           tilePositionY, zoom);

                tileImageLayerSources.Add(new Uri(url));
            }
        }

        private static string TileXYToQuadKey(int tileX, int tileY, int levelOfDetail)
        {
            var quadKey = new StringBuilder();
            for (int i = levelOfDetail; i > 0; i--)
            {
                char digit = '0';
                int mask = 1 << (i - 1);
                if ((tileX & mask) != 0)
                {
                    digit++;
                }
                if ((tileY & mask) != 0)
                {
                    digit++;
                    digit++;
                }
                quadKey.Append(digit);
            }
            return quadKey.ToString();
        }

        //public override void ValidateMapMode(MapMode mode)
        //{
        //    MDSMapModeFactory.ValidateMode(mode);
        //}
    }
}